#include "pch.h"
#include "CppUnitTest.h"
#include <tchar.h>
#include "WaitForTask.h"
#include <tchar.h>

using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace RSSParser::ViewModels;
using namespace Windows::System::Threading;
using namespace concurrency;


namespace UnitTests
{
    TEST_CLASS(FeedInfoTests)
    {
    public:

		TEST_CLASS_INITIALIZE(InitTestClass)
		{
			RSSParser::Settings::MobilitySettings::Uri = "https://readability.com/api/content/v1/parser?token=1eced84b6c4c07896c3c2140887b34acbe10af25&url=";
			RSSParser::Settings::MobilitySettings::UserAgent = "Win8NewsReader - 88c1a20e-136c-4e19-9e84-971549ad74d2";
			RSSParser::Settings::MobilitySettings::Name = "Mobility";
		}

        TEST_METHOD(ShouldLoadFeed)
        {
            auto fi = ref new FeedInfo("http://news.yahoo.com/rss/most-popular");
			auto t = create_task([fi] () -> void
			{
				while(!fi->IsLoaded && fi->Error == nullptr)
				{
				}
			});
			fi->BeginLoad();
			bool success;
			WaitForTask(t, success, 1500);
			
			Assert::IsTrue(success, _T("Operation timed-out."));
			Assert::IsTrue(fi->IsLoaded);
			Assert::AreEqual("Most Popular News Headlines - Yahoo! News", fi->Title);
			Assert::AreEqual("View the most popular news headlines on Yahoo! News. Discover which headlines and stories our users found most interesting.", fi->Description);
        }

		TEST_METHOD(ShouldGetFeedItems)
        {
            auto fi = ref new FeedInfo("http://news.yahoo.com/rss/most-popular");
			auto t = create_task([fi] () -> void
			{
				while(!fi->IsLoaded && fi->Error == nullptr)
				{
				}
			});
			
			fi->BeginLoad();
			bool success;
			WaitForTask(t, success, 0);

			auto size = fi->FeedItems->Size;
			for(unsigned int i =0 ;i<size;i++)
			{
				auto feedItem = fi->FeedItems->GetAt(i);
				if(feedItem->Link != nullptr)
				{
					if(!feedItem->FullTextLoaded)
					{
						auto t2 = create_task([feedItem] () -> void
						{
							while(!feedItem->FullTextLoaded && feedItem->FullTextError == nullptr)
							{
							}
						});

						feedItem->LoadFullTextAsync();
						success = true;
						WaitForTask(t2, success, 0);
					}
			
					Assert::IsNotNull(feedItem->FullText);
				}
			}
        }
    };
}